from django.shortcuts import render, redirect, get_object_or_404
from df_user.forms import UserForm
from hashlib import sha1
from df_user.models import UserInfo, UserAddressInfo
from df_order.models import OrderInfo,OrderDetailInfo
from django.http import JsonResponse
from df_goods.models import *

def is_login(func):
    # 判断是否登录状态的装饰器
    def inner(request, *args, **kwargs):
        if request.session.get('user_id'):
            # 如果用户已登录
            return func(request, *args, **kwargs)
        else:
            # 如果没有登录 重定向到登录页面
            if request.is_ajax():
                return JsonResponse({'isLogin': 0})
            return redirect('login')

    return inner


# Create your views here.
def register(request):
    form = UserForm()
    return render(request, 'df_user/register.html', {'form': form})


def check_register(request):
    dict1 = request.POST
    upwd = dict1.get('upwd')
    form = UserForm(request.POST)

    if form.is_valid():
        user = form.save(commit=False)
        s1 = sha1() #创建一个sha1对象
        s1.update(upwd.encode())
        upwd = s1.hexdigest()  # 获取到加密后的密码
        user.upwd = upwd
        user.save()  # 注册成功
        return redirect('login')
    return render(request, 'df_user/register.html', {'form': form})


def user_check(request):
    uname = request.GET.get('uname')
    xxx = UserInfo.objects.filter(uname=uname).count()  # 根据用户名查找用户 个数
    return JsonResponse({'num': xxx})


def login(request):
    #如果有记住用户名，就能读取用户名，如果没有就为空
    uname = request.COOKIES.get('uname')
    return render(request, 'df_user/login.html', {'title': '登录', 'error_name': 0, 'error_pwd': 0, 'uname': uname})


def login_check(request):
    dict1 = request.POST
    uname = dict1.get('username')
    upwd = dict1.get('pwd')
    jizhu = dict1.get('jizhu', 0)
    users = UserInfo.objects.filter(uname=uname)  # 根据用户名查找用户
    if users:
        s1 = sha1()
        s1.update(upwd.encode())
        if s1.hexdigest() == users[0].upwd:
            # 登录成功
            res = redirect('info')  # 跳转到用户中心
            if jizhu:
                # 如果点了记住用户名
                res.set_cookie('uname', uname)
            else:
                res.set_cookie('uname', uname, max_age=-1)  # 到浏览器关闭
            request.session['user_id'] = users[0].id
            request.session['user_name'] = uname
            return res
        else:
            # 密码不对
            context = {'title': '登录', 'error_name': 0, 'error_pwd': 1, 'uname': uname}
            return render(request, 'df_user/login.html', context)
    else:
        # 没有找到用户
        context = {'title': '登录', 'error_name': 1, 'error_pwd': 0, 'uname': uname}
        return render(request, 'df_user/login.html', context)

#访问用户中心页面和用户地址页面，前提是要登录了，所以用is_log

#@is_login
def info(request):
    id = request.session.get('user_id')
    user = UserInfo.objects.get(id=id)
    try:
        user_addr = UserAddressInfo.objects.filter(user=user)
        print()
        jin = request.COOKIES.get('jin', '[]')
        jin_list = eval(jin)  # 读取的jin是字符串，要用eval转为可执行的列表
        # 用列表推导式生成最近浏览的商品列表
        goods = [GoodsInfo.objects.get(pk=id) for id in jin_list]
        return render(request, 'df_user/user_center_info.html',
                      {'title': '用户中心', 'goods': goods, 'user': user, 'user_addr': user_addr})
        # return render(request, 'df_user/login.html', {'title': '用户中心', 'goods': goods, 'user_addr': user_addr})

    except UserAddressInfo.DoesNotExist:
        user_addr = {}
        jin = request.COOKIES.get('jin', '[]')
        jin_list = eval(jin)  # 读取的jin是字符串，要用eval转为可执行的列表
        # 用列表推导式生成最近浏览的商品列表
        goods = [GoodsInfo.objects.get(pk=id) for id in jin_list]
        return render(request, 'df_user/user_center_info.html',
                      {'title': '用户中心', 'goods': goods, 'user': user, 'user_addr': user_addr})
        # return render(request, 'df_user/login.html', {'title': '用户中心', 'goods': goods, 'user_addr': user_addr})

    # print(user_addrs)
    # user_addr = user_addrs[0]
    #user_addr = get_object_or_404(UserAddressInfo, user_id=user.id)
    # if user_addrs:
    #     user_addr = user_addrs[0]
    # else:
    #     user_addr = {}
    # 最近浏览



#收获地址页面
# @is_login
# def site(request):
#     id = request.session.get('user_id')
#     print('--------------------------------')
#     print(id)
#     user = UserInfo.objects.get(id=id)
#     user_addr = user.useraddressinfo_set.all()
#     str1 = ''
#     if user_addr:
#         user_addr = user_addr[0]
#         str1 = f'{user_addr.uaddress},({user_addr.uname})收,电话:{user_addr.uphone}'
#     return render(request, 'df_user/user_center_site.html', {'str1': str1})

@is_login
def site(request):
    if request.method == 'GET':
        id = request.session.get('user_id')
        user = UserInfo.objects.get(id=id)
        addres = user.useraddressinfo_set.all()
        # addres = UserAddressInfo.objects.filter(auser_id=UserInfo.objects.get(user_name=user_name).id)
        return render(request, 'df_user/user_center_site.html', {'addres': addres})
    else:
        # user_name = request.session.get('user_names')
        id = request.session.get('user_id')
        users = UserInfo.objects.get(id=id)
        dict1 = request.POST
        aname = dict1.get('aname')
        ahome = dict1.get('ahome')
        # aemailnum = dict1.get('aemailnum')
        aphone = dict1.get('aphone')

        areas = UserAddressInfo()
        areas.uname = aname
        areas.uaddress = ahome
        # areas.aemailnum = aemailnum
        areas.uphone = aphone
        areas.user_id = users.id
        areas.save()
        return render(request, 'df_user/user_center_site.html')

def shou_save(request):
    dict1 = request.POST
    ushou = dict1.get('shou')
    uaddr = dict1.get('addr')
    ucode = dict1.get('ucode')
    uphone = dict1.get('uphone')
    id = request.session.get('user_id')
    user = UserInfo.objects.get(id=id)
    u_addr = UserAddressInfo()
    u_addr.uname = ushou
    u_addr.uaddress = uaddr
    u_addr.uphone = uphone
    u_addr.user = user
    u_addr.save()
    id = request.session.get('user_id')
    user = UserInfo.objects.get(id=id)
    addres = user.useraddressinfo_set.all()
    # addres = UserAddressInfo.objects.filter(auser_id=UserInfo.objects.get(user_name=user_name).id)
    return render(request, 'df_user/user_center_site.html', {'addres': addres})


# 我的订单页面
@is_login
def user_center_order(request):
    user_names = request.session.get('user_names')
    id = request.session.get('user_id')
    user = UserInfo.objects.get(id=id)
    # print(user_names)
    # print("*******")
    # user = UserInfo.objects.get(uname=user_names)
    order = OrderInfo.objects.filter(user_id=user.id)
    return render(request, 'df_user/user_center_order.html',{"orders":order})

def logout(request):
    request.session.flush()
    user_name = ''
    if request.method == 'GET':
        if request.COOKIES.get('user_name'):
            user_name = request.COOKIES.get('user_name')
    return render(request, 'df_user/login.html', {'user_name': user_name})